<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PHP Error Handling</title>
</head>
<body>
<h1>PHP Error Handling</h1>

<div>
    <h3>Basic Error Handling: Using the die() function</h3>
    <?php
    //$file = fopen("welcome.txt","r");
    //    if(!file_exists("welcome.txt")){
    //        die("File not found");
    //    }else{
    //        $file = fopen("welcome.txt","r");
    //    }
    ?>
</div>
<div>
    <h3>Creating a Custom Error Handler</h3>
    <?php
    /*
     * error_function(error_level,error_message,
     * error_file,error_line,error_context)
     * */
    function customError($errorNo, $errorStr)
    {
        $errLevel = array(2 => "E_WARNING", 8 => "E_NOTICE", 256 => "E_USER_ERROR",
            512 => "E_USER_WARNING", 1024 => "E_USER_NOTICE", 4096 => "E_RECOVERABLE_ERROR", 8191 => "E_ALL");
        echo("<b>Error:</b>" . $errorNo . " = " . $errLevel[$errorNo] . "<br>");
        echo("Message: " . $errorStr);
        echo("Ending Script");
        die();
    }

    ?>
</div>
<div>
    <h3>Set Error Handler</h3>
    <?php
    set_error_handler("customError");
    ?>
</div>
<div>
    <h3>Example</h3>
    <?php
    //error handler function
    //echo($test);
    ?>
</div>
<div>
    <h3>Trigger an Error</h3>
    <?php
    //    $test = 2;
    //    if($test>1){
    //        trigger_error("Value must be 1 or below");
    //    }
    ?>
</div>
<div>
    <h4>This example an E_USER_WARNING occurs if the "test" variable is bigger than "1". If an E_USER_WARNING occurs we
        will use our custom error handler and end the script:</h4>
    <?php
    //set error handler
    set_error_handler("customError", E_USER_WARNING); //Tức là chỉ lỗi E_USER_WARNING mới bắt

    //trigger error
    //    $test=2;
    //    if ($test>1) {
    //        //trigger_error("Value must be 1 or below"); Nếu ko có E_USER_WARNING thì customError ko bắt
    //        trigger_error("Value must be 1 or below",E_USER_WARNING);
    //    }
    ?>
</div>
<div>
    <h3>Send an Error Message by E-Mail</h3>
    <?php
    //error handler function
    function customError1($errno, $errstr)
    {
        echo "<b>Error:</b> [$errno] $errstr<br>";
        echo "Webmaster has been notified";
        error_log("Error: [$errno] $errstr", 1,
            "duc01226@yahoo.com", "From: webmaster@example.com");
    }

    ;

    //set error handler
    set_error_handler("customError1", E_USER_WARNING);

    //trigger error
    $test = 2;
    if ($test > 1) {
        trigger_error("Value must be 1 or below", E_USER_WARNING);
    }
    ?>
</div>
</body>
</html>